import 'package:get/get.dart';
import 'package:jump_scape/js_data/js_box/js_init.dart';

import '../objectbox.g.dart';
import 'js_box/js_game_record.dart';

class JsGame {
  Future<bool> createGameRecordSpring({
    required int time,
  }) async {
    final userId = (await JsObjectBox.setting).userId;

    if (userId.isEmpty) {
      return false;
    }

    final box = GameRecordBox.create(userId: userId, time: time, gameType: 'Spring');
    box.id = JsObjectBox.gameRecordBox.put(box);

    return true;
  }

  Future<bool> createGameRecordWinter({
    required int time,
  }) async {
    final userId = (await JsObjectBox.setting).userId;

    if (userId.isEmpty) {
      return false;
    }

    final box = GameRecordBox.create(userId: userId, time: time, gameType: 'Winter');
    box.id = JsObjectBox.gameRecordBox.put(box);

    return true;
  }

  Future<bool> createGameRecordCity({
    required int time,
  }) async {
    final userId = (await JsObjectBox.setting).userId;

    if (userId.isEmpty) {
      return false;
    }

    final box = GameRecordBox.create(userId: userId, time: time, gameType: 'City');
    box.id = JsObjectBox.gameRecordBox.put(box);

    return true;
  }

  Future<void> quaryGameRecord({
    required String gameType,
    required Function(List<GameRecordBox> list) call,
  }) async {
    final box = JsObjectBox.gameRecordBox.query(GameRecordBox_.gameType.equals(gameType)).order(GameRecordBox_.time, flags: Order.descending).build();
    final list = box.find();
    box.close();

    final members = JsObjectBox.memberBox.getAll();

    list.forEach((gameRecord) {
      try {
        gameRecord.member = members.firstWhere((member) => gameRecord.userId == member.userId);
      } catch (e) {}
    });

    try {
      call(list);
    } catch (e) {}
  }

  Future<bool> deleteByUserId({
    required String userId,
  }) async {
    try {
      final box = JsObjectBox.gameRecordBox.query(GameRecordBox_.userId.equals(userId)).build();
      box.remove();
      box.close();

      return true;
    } catch (e) {
      e.printError();

      return false;
    }
  }
}
